package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrdersService;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@RestController
@Slf4j
@RequestMapping("/order")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("订单数据:{}", orders);
        ordersService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 后端订单信息分页查询,
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String number, String beginTime, String endTime) {
        //查询全部订单,将订单封装到page中返回回去
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        //模糊查询number订单号,范围查询时间内的订单信息
        lqw.like(number != null, Orders::getNumber, number);
        //查询下单时间内的订单信息
        lqw.gt(beginTime != null, Orders::getOrderTime, beginTime)
                .lt(endTime != null, Orders::getOrderTime, endTime);
        //条件查询出的订单数据,分装到page中返回
        Page<Orders> ordersPage = ordersService.page(pageInfo, lqw);

        return R.success(ordersPage);
    }

    /**
     * 前端订单信息分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> userPage(int page, int pageSize) {
        //获取用户id,根据用户id查询用户的所有订单,按最后操作时间排序.
        Page<Orders> orderPages = new Page<>(page,pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Orders::getUserId, BaseContext.getCurrentId());
        lqw.orderByAsc(Orders::getOrderTime);
        ordersService.page(orderPages,lqw);
        //对象拷贝,将订单信息拷贝给Dto,再将订单菜品信息添加到Dto中
        BeanUtils.copyProperties(orderPages,ordersDtoPage,"records");
        //根据订单号查询订单菜品信息,将订单菜品信息添加到Dto中
        List<Orders> records = orderPages.getRecords();
        List<OrdersDto> ordersDtoList = records.stream().map(item -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            //根据id查询订单菜品信息
            LambdaQueryWrapper<OrderDetail> lqw2 = new LambdaQueryWrapper<>();
            lqw2.eq(OrderDetail::getOrderId, item.getId());
            List<OrderDetail> list = orderDetailService.list(lqw2);
            ordersDto.setOrderDetails(list);
            return ordersDto;
        }).collect(Collectors.toList());

        ordersDtoPage.setRecords(ordersDtoList);
        return R.success(ordersDtoPage);
    }

    /**
     * 修改订单状态
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> status(@RequestBody Orders orders){
        ordersService.updateById(orders);
        return R.success("操作成功");
    }

    /**
     * 再来一单
     * @param map
     * @return
     */
    @PostMapping("/again")
    public R<String> again(@RequestBody Map map){
        //前端就传过来个订单id,要根据订单id找到订单菜品,将菜品再次添加到购物车,还是JSON格式,
        log.info("再来一单:{}",map.get("id"));
        LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OrderDetail::getOrderId,map.get("id"));
        List<OrderDetail> orderDetailList = orderDetailService.list(lqw);
        //遍历集合将菜品或者套餐信息拷贝给shoppingCart中,将shoppingCart返回回去
        //根据订单id获取用户id,将用户id赋值给购物车的用户id
        LambdaQueryWrapper<Orders> lqw2 = new LambdaQueryWrapper<>();
        lqw2.eq(Orders::getId,orderDetailList.get(0).getOrderId());
        Long userId = ordersService.getOne(lqw2).getUserId();
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(item -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(item, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            return shoppingCart;
        }).collect(Collectors.toList());
        //不要在循环里面做操作~~~!!!
        shoppingCartService.saveBatch(shoppingCartList);
        //重新添加之后不需要返回购物车数据,前端会跳到首页面,会重新查看购物车~~~多看看代码~~~
        return R.success("OK");
    }
}
